# -*- coding: utf-8 -*-
import copy
import json
import math
from zc_core.util.common import parse_int, parse_number
from zc_core.model.items import Catalog, ItemData, Sku
from zc_core.util.http_util import *
from zc_core.util.encrypt_util import md5
from zc_core.util.sku_id_parser import convert_id2code

from zc_core.pipelines.helper.catalog_helper import CatalogHelper


# 解析catalog列表
def parse_catalog(response, cat1_white_list):
    # 全量分类
    cats = list()
    # 待采集三级分类
    todo_cats = list()
    json_data = json.loads(response.text)

    for cat1 in json_data:
        # 一级分类
        cat1_id = cat1.get('innercode')
        cat1_name = cat1.get('category_name')
        rs_cat1 = _build_catalog(cat1_id, cat1_name, '', 1)
        cats.append(rs_cat1)

        for cat2_items in cat1.get('childs', []):
            # 二级分类
            cat2_id = cat2_items.get('innercode')
            cat2_name = cat2_items.get('category_name')
            rs_cat2 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(rs_cat2)

            for cat3_itmes in cat2_items.get('childs', []):
                # 三级分类
                cat3_id = cat3_itmes.get('innercode')
                cat3_name = cat3_itmes.get('category_name')
                rs_cat3 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                cats.append(rs_cat3)
                # 采集目标
                if cat1_id in cat1_white_list:
                    todo_cats.append(rs_cat3)

    return cats, todo_cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


# 维度：三级分页，解析sku列表页数
def parse_total_page(response):
    rs = json.loads(response.text)
    total_page = rs.get('result', {}).get('pageTotal', 0)

    return total_page


# 维度：品牌，解析sku列表页数
def parse_brand_total_page(response):
    page_json = json.loads(response.text)
    total_page = page_json['result']['pageTotal']

    return total_page


# 解析阶梯价格页数
def parse_price_page(num, size=20):
    return math.ceil(num / size)


def parse_price_page_xx(response):
    return json.loads(response.text)['result']['totalCount']


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    cat3_id = meta.get('catalog3Id')
    cataloger_help = CatalogHelper()
    skus = list()
    rs = json.loads(response.text)
    if rs.get('result', {}):
        for row in rs.get('result', {}).get('data', []):
            sku = Sku()
            sku['batchNo'] = batch_no
            sku['skuId'] = str(row.get('skuid'))
            sku['catalog3Id'] = str(cat3_id)
            cataloger_help.fill(sku)
            sku['spuId'] = str(row.get('id', ''))
            sku['unit'] = row.get('unit', '')
            sku['skuName'] = row.get('title', '')
            sku['supplierSkuCode'] = convert_id2code('deli', row.get('skucode', ''))
            sku['supplierSkuId'] = row.get('skucode', '')
            sku['skuCode'] = row.get('code', '')
            sku['supplierId'] = str(row.get('supplier_id', ''))
            # sp_name = row.get('supply_shortName')
            # if not sp_name:
            #     sp_name = row.get('supplier_name', '')
            # sku['supplierName'] = sp_name
            sku['stock'] = parse_int(row.get('stock', 0))
            sku['soldCount'] = row.get('sales_volume', 0)
            sku['originPrice'] = row.get('open_price')
            sku['salePrice'] = row.get('tax_price')
            skus.append(sku)

    return skus


# 解析出所有品牌
def parse_all_brand(response):
    all_brand_json = json.loads(response.text)
    all_list = []
    if all_brand_json['result'].get('aggResult', '').__len__() != 0:
        all_list = [[j['termValue'] for j in i['termValues']] for i in all_brand_json['result']['aggResult'] if
                    '品牌' in i.values()]
    return False if len(all_list) == 0 else (True, all_list[0])


# 解析stock
def parse_stock(response):
    if response.text and 'True' in response.text:
        return True
    return False


# 查询商品主体，属性中的key对应的value
def select_nature(goods_json_data, select_list):
    Model = ''
    for index, i in enumerate(goods_json_data['specifications']['groups']):
        Model_list = [k for k in [j for j in i['group_items']] if len(set(select_list) & set(k.values())) != 0]
        Model = (Model_list[0].get('value') if Model_list.__len__() != 0 else '') + Model
    return Model


# 查询价格区间
def parse_price_range(response):
    rs = json.loads(response.text)
    filters = rs.get('result', {}).get('aggResult', [])
    for filter in filters:
        if filter.get('termsCode') == 'tax_price' or filter.get('termsName') == '价格':
            filter_list = list()
            for filter_item in filter.get('termValues', []):
                label = filter_item.get('termValue', '')
                if label and '~' in label:
                    arr = label.split('~')
                    filter_item['startPrice'] = parse_int(arr[0])
                    filter_item['endPrice'] = parse_int(arr[1])
                else:
                    filter_item['startPrice'] = parse_int(label.replace('以上', ''))
                    filter_item['endPrice'] = 99999999
                filter_item['termsCode'] = 'tax_price'
                filter_item['termsName'] = '价格'
                filter_list.append(filter_item)

            return filter_list

    return []


# 查询价格区间
def split_filter(filter):
    if filter:
        start = filter.get('startPrice')
        end = filter.get('endPrice')

        if end - start in [0, 1]:
            return None, None

        f1 = copy.copy(filter)
        delta = math.ceil((end - start) / 2)
        f1['startPrice'] = start
        f1['endPrice'] = start + delta
        f1['termValue'] = f'{f1["startPrice"]}~{f1["endPrice"]}'

        f2 = copy.copy(filter)
        # delta = math.floor((end - start) / 2)
        f2['startPrice'] = start + delta
        f2['endPrice'] = end
        f2['termValue'] = f'{f2["startPrice"]}~{f2["endPrice"]}'

        return f1, f2


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    originPrice = meta.get('originPrice')
    salePrice = float(meta.get('salePrice'))

    goods_json_data = json.loads(response.text)['data']
    if goods_json_data:
        result = ItemData()
        # 批次编号
        result['batchNo'] = batch_no
        # 平台商品ID（用于业务系统）
        result['skuId'] = sku_id
        # 平台商品名称（标题） #TODO
        skuName = goods_json_data.get('title', None)
        if skuName:
            result['skuName'] = skuName
        else:
            skuName = goods_json_data.get('productSubject', None)
            if skuName:
                result['skuName'] = skuName
        result['skuCode'] = goods_json_data['unified_code']
        # 供应商商品编码
        result['supplierSkuId'] = goods_json_data['skuCode']
        # 供应商商品编号（无后缀）
        result['supplierSkuCode'] = goods_json_data['skuCode']
        if goods_json_data['supply_shortName']:
            if goods_json_data['supply_shortName'].strip() == '得力集团有限公司' or '得力':
                plat_code = 'deli'
                result['supplierSkuCode'] = convert_id2code(plat_code, goods_json_data['skuCode'])
        # 供应商名字
        supplierName = goods_json_data['supply_shortName']
        if not supplierName:
            supplierName = goods_json_data['supplier']['supplier_name']
        result['supplierName'] = supplierName
        # 供应商ID
        result['supplierId'] = str(goods_json_data['supplier'].get('supplier_id'))
        # 供应商编号(常用于数据采集)
        result['supplierCode'] = goods_json_data['supplier'].get('supplier_code')
        # 交付时间
        deliveryDay = goods_json_data['deliveryTime']
        if deliveryDay:
            result['deliveryDay'] = deliveryDay
        # 产品型号
        unit = goods_json_data['unit'].strip()
        if unit:
            result['unit'] = unit
        # 主图列表
        skuImg = goods_json_data['main_picture']
        if skuImg:
            skuImg = skuImg.get('uri_large').strip()
            result['skuImg'] = fill_link(url=skuImg, base='https://ego.ctg.com.cn')
        brand_name = goods_json_data['brand'].get('brand_name', '')
        if brand_name:
            brandName = brand_name.replace('</li>', '').strip()
            # 品牌名称
            result['brandName'] = brandName
            # 品牌ID
            result['brandId'] = md5(brandName)
        # 三级分类名称
        result['catalog3Name'] = goods_json_data['category'].get('category_name')
        # TODO 三级分类id(cateCode)
        result['catalog3Id'] = goods_json_data['category'].get('innercode')
        # 在售状态
        result['saleStatus'] = goods_json_data['status']
        # 累计销售
        result['soldCount'] = goods_json_data['sales']
        # 销售价格
        result['salePrice'] = salePrice
        # 商品原价
        if originPrice in [0.0, 0.00, 0, '0.0', '0.00', '0', '']:
            originPrice = salePrice
        result['originPrice'] = float(originPrice)
        # TODO （catalogId）
        catalogCode = goods_json_data['category'].get('category_id')
        # 最小起订量
        minBuy = select_nature(goods_json_data, ['最小起订量', '最低起订量']).strip()
        if minBuy:
            result['minBuy'] = minBuy
        # 型号
        brandModel = select_nature(goods_json_data, ['产品型号', '型号', ' 型号', '型号 '])
        if brandModel:
            result['brandModel'] = brandModel.replace('</li>', '').strip()
        # 规格参数
        # attrs = goods_json_data['specifications']['groups']
        # result['attrs'] = attrs
        return result


if __name__ == '__main__':
    pass
